import traceback

from apscheduler.schedulers.background import BackgroundScheduler
from datetime import datetime
from database import Database
from docker_managent import DockerManager

# 任务状态定义
JOB_STATUS = {
    'NOT_STARTED': 0,    # 未启动
    'RUNNING': 1,        # 运行中
    'COMPLETED': 100,    # 完成
    'ERROR': 99         # 错误
}

# 创建后台调度器实例和Docker管理器实例
scheduler = BackgroundScheduler()
docker_manager = DockerManager()

def print_with_time(message):
    """打印带时间戳的日志信息"""
    print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] {message}")

def process_job(db, job):
    """处理单个同步任务，执行镜像同步并更新任务状态"""
    try:
        source_config = {
            "host": job['source_host'],
            "port": job['source_port'],
            "username": job['source_username'],
            "password": job['source_password']
        }
        
        target_config = {
            "host": job['target_host'],
            "port": job['target_port'],
            "username": job['target_username'],
            "password": job['target_password']
        }

        # 将任务状态更新为运行中
        db.update_job_status(job['id'], JOB_STATUS['RUNNING'], 0)

        # 解析 projects 字段为数组
        projects = job['projects'].split(',') if job['projects'] else []

        # 执行镜像同步操作
        success, message = docker_manager.sync_image(source_config, target_config, projects)
        
        # 根据同步结果更新任务状态
        if success:
            db.update_job_status(job['id'], JOB_STATUS['COMPLETED'], 100)
        else:
            # 同步失败：状态设为错误，进度设为100，记录错误信息
            db.update_job_status(job['id'], JOB_STATUS['ERROR'], 100, f"同步失败: {message}")

        print_with_time(f"任务 {job['name']} 处理结果: {message}")

    except Exception as e:
        error_message = f"处理任务时出错: {str(e)}"
        print_with_time(f"任务 {job['name']} {error_message}")
        # 处理过程中出现异常：状态设为错误，进度设为100
        db.update_job_status(job['id'], JOB_STATUS['ERROR'], 100, error_message)
        traceback.print_exc()

def check_jobs_status(db, jobs):
    """检查并处理所有未开始的同步任务"""
    try:
        print_with_time("任务检查开始")
        if jobs:
            print_with_time(f"发现 {len(jobs)} 个未开始的任务:")
            for job in jobs:
                print_with_time(
                    f"任务详情: [ID:{job['id']}] [名称:{job['name']}] [进度:{job['progress']}%] [状态:{job['status']}] "
                    f"[错误:{job['error_message'] if job['error_message'] else '无'}] "
                    f"[源主机: {job['source_host']}:{job['source_port']} {job['source_username']}] "
                    f"[目标主机: {job['target_host']}:{job['target_port']} {job['target_username']}]"
                )
                process_job(db, job)
        else:
            print_with_time("未检测到需要处理的任务")
    except Exception as e:
        print_with_time(f"检查任务状态时出错: {e}")
        traceback.print_exc()

def init_scheduler(database_path):
    """初始化定时任务，每5秒检查一次未开始的任务"""
    if not scheduler.running:
        # 创建 Database 实例
        db = Database(database_path)
        # 将 db 实例作为参数传递给 check_jobs_status 函数
        scheduler.add_job(
            check_jobs_status, 
            'interval', 
            seconds=5,
            args=[db, db.get_jobs_by_status(JOB_STATUS['NOT_STARTED'])]
        )
        # 启动调度器
        scheduler.start()
        print_with_time("调度器已启动")